#include "my_stdio.h"
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

mFILE* Myfopen(const char* path,const char* mod)
{
    int fd = -1;
    int flag;
    if(strcmp(mod,"r") == 0)
    {
        flag = O_RDONLY;
        fd = open(path,flag);
    }
    else if(strcmp(mod,"w") == 0)
    {
        flag = O_CREAT | O_WRONLY | O_TRUNC;
        fd = open(path,flag,0666);
    }
    else if(strcmp(mod,"a") == 0)
    {
        flag = O_CREAT | O_WRONLY | O_APPEND; 
        fd = open(path,flag,0666);
    } 
    else 
    {
        //...
    }
    if(fd < 0)
        return NULL;
    mFILE* pf = (mFILE*)malloc(sizeof(mFILE));
    if(pf == NULL)
    {
        close(fd);
        return NULL;
    }
    pf->fileno = fd;
    pf->flag = flag;
    pf->flush_mode = FLUSH_LINE;
    pf->size = 0;
    return pf;
}

void Myfflush(mFILE* f)
{
    write(f->fileno,f->buffer,f->size);
    f->size = 0;
    fsync(f->fileno);
}

void Myfwrite(const char* str,int len,mFILE* f)
{
    int j = 0;
    while(j < len)
    {
        int i = f->size;
        for(;i < SIZE &&  j  < len; i++,j++)
        {
            f->buffer[i] = str[j];
        }
        f->size = i;
        if(i == SIZE)
        {
            Myfflush(f);
        }
    }

    if(f->flush_mode == FLUSH_LINE && f->buffer[f->size - 1] == '\n')
    {
        Myfflush(f);
    }
}

void Myfclose(mFILE* f)
{
    if(f->size > 0)
        Myfflush(f);
    close(f->fileno);
    free(f);
}




